package es.buffygilmore.collectionapp;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import es.buffygilmore.collectionapp.dialog.ConfirmacionEliminarDialogFragment;
import es.buffygilmore.collectionapp.vo.Elemento;

public class ElementoEdit extends FragmentActivity implements
		ConfirmacionEliminarDialogFragment.NoticeDialogListener {

	private static final int REQUEST_IMAGE_CAPTURE = 1;

	private static final String JPEG_FILE_PREFIX = "IMG_";
	private static final String JPEG_FILE_SUFFIX = ".jpg";

	private static final String CURRENTPHOTOPATH_KEY = "currentPhotoPath";

	private EditText mTitleText;
	private EditText mDescripcionText;
	private Long mRowId;
	private Long mIdColeccion;
	private CollectionAppDbAdapter mDbHelper;

	private ImageView mImageView;

	private String mCurrentPhotoPath;

	private ImageView confirmButton;

	private ImageView eliminarButton;

	private ImageView picSBtn;

	@Override
	protected void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.mDbHelper = new CollectionAppDbAdapter(this);

		this.mDbHelper.open();

		this.setContentView(R.layout.edicion_elemento);
		this.setTitle(R.string.edit_note);

		this.mTitleText = (EditText) this.findViewById(R.id.titulo_elemento);
		this.mDescripcionText = (EditText) this.findViewById(R.id.descripcion_elemento);

		this.confirmButton = (ImageView) this.findViewById(R.id.guardar_elemento);
		this.eliminarButton = (ImageView) this.findViewById(R.id.eliminar_elemento);
		this.eliminarButton.setEnabled(false);
		this.eliminarButton.setColorFilter(0x55BD8ED7, PorterDuff.Mode.MULTIPLY);

		this.mRowId = (savedInstanceState == null) ? null : (Long) savedInstanceState
				.getSerializable(CollectionAppDbAdapter.KEY_ELEMENTO_ROWID);
		final Bundle extras = this.getIntent().getExtras();
		if (this.mRowId == null) {
			this.mRowId = extras != null
					&& extras.getLong(CollectionAppDbAdapter.KEY_ELEMENTO_ROWID) != 0 ? extras
							.getLong(CollectionAppDbAdapter.KEY_ELEMENTO_ROWID) : null;
		}

		// Recupera el idColeccion
		this.mIdColeccion = extras != null ? extras
				.getLong(CollectionAppDbAdapter.KEY_ELEMENTO_COLECCION) : null;
		this.mImageView = (ImageView) this.findViewById(R.id.vista_foto);

		this.picSBtn = (ImageView) this.findViewById(R.id.sacar_foto);
		this.setBtnListenerOrDisable(this.picSBtn, this.mTakePicSOnClickListener,
				MediaStore.ACTION_IMAGE_CAPTURE);

		this.populateFields();

		this.confirmButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(final View view) {
				ElementoEdit.this.confirmButton
						.setColorFilter(0xEEBD8ED7, PorterDuff.Mode.MULTIPLY);
				ElementoEdit.this.saveState();
				ElementoEdit.this.setResult(RESULT_OK);
				ElementoEdit.this.finish();
			}

		});

		this.eliminarButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(final View view) {
				ElementoEdit.this.eliminarButton.setColorFilter(0xEEBD8ED7,
								PorterDuff.Mode.MULTIPLY);

				ElementoEdit.this.showConfirmDialog();
				ElementoEdit.this.eliminarButton.clearColorFilter();

			}

				});

	}

	private void populateFields() {
		if (this.mRowId != null) {
			final Cursor elemento = this.mDbHelper.obtenerElemento(this.mRowId);
			this.startManagingCursor(elemento);
			this.mTitleText.setText(elemento.getString(elemento
					.getColumnIndexOrThrow(CollectionAppDbAdapter.KEY_ELEMENTO_NOMBRE)));
			this.mDescripcionText.setText(elemento.getString(elemento
					.getColumnIndexOrThrow(CollectionAppDbAdapter.KEY_ELEMENTO_COMENTARIO)));
			this.mCurrentPhotoPath = elemento.getString(elemento
					.getColumnIndexOrThrow(CollectionAppDbAdapter.KEY_ELEMENTO_RUTA_IMAGEN));
			if (this.mCurrentPhotoPath != null && !"".equals(this.mCurrentPhotoPath)) {

				this.setPic();
			}
			this.eliminarButton.setEnabled(true);
			this.eliminarButton.clearColorFilter();
		}
	}

	@Override
	protected void onSaveInstanceState(final Bundle outState) {
		outState.putString(CURRENTPHOTOPATH_KEY, this.mCurrentPhotoPath);
		super.onSaveInstanceState(outState);
		// this.saveState();
		outState.putSerializable(CollectionAppDbAdapter.KEY_ELEMENTO_ROWID, this.mRowId);
	}

	@Override
	protected void onRestoreInstanceState(final Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
		this.mCurrentPhotoPath = savedInstanceState.getString(CURRENTPHOTOPATH_KEY);
		// this.setPic();
	}

	@Override
	protected void onPause() {
		super.onPause();
		// this.saveState();
	}

	@Override
	protected void onResume() {
		super.onResume();
		this.populateFields();
	}

	private void saveState() {
		final Elemento elemento = new Elemento();
		elemento.setNombre(this.mTitleText.getText().toString());
		elemento.setComentario(this.mDescripcionText.getText().toString());
		elemento.setPropiedad(1);
		elemento.setIdColeccion(this.mIdColeccion);
		elemento.setRutaImagen(this.mCurrentPhotoPath);

		if ((elemento.getNombre() != null && !"".equals(elemento.getNombre()))
				|| (elemento.getComentario() != null && !"".equals(elemento.getComentario()))
				|| (elemento.getRutaImagen() != null && !"".equals(elemento.getRutaImagen()))) {

			if (this.mRowId == null) {
				final long id = this.mDbHelper.crearElemento(elemento);
				if (id > 0) {
					this.mRowId = id;
				}
			} else {
				this.mDbHelper.modificarElemento(this.mRowId, elemento);
			}
		}
	}

	private void dispatchTakePictureIntent() {
		final Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		if (takePictureIntent.resolveActivity(this.getPackageManager()) != null) {
			File f = null;

			try {
				f = this.setUpPhotoFile();
				this.mCurrentPhotoPath = f.getAbsolutePath();
				takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
			} catch (final IOException e) {
				e.printStackTrace();
				f = null;
				this.mCurrentPhotoPath = null;
			}
			this.startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
		}
	}

	@Override
	protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
		this.confirmButton.clearColorFilter();
		this.picSBtn.clearColorFilter();
		this.eliminarButton.clearColorFilter();
		if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
			// final Bundle extras = data.getExtras();
			// final Bitmap imageBitmap = (Bitmap) extras.get("data");
			// this.mImageView.setImageBitmap(imageBitmap);
			this.handleBigCameraPhoto();
		}
	}

	ImageView.OnClickListener mTakePicSOnClickListener = new ImageView.OnClickListener() {
		@Override
		public void onClick(final View v) {
			ElementoEdit.this.picSBtn.setColorFilter(0xEEBD8ED7, PorterDuff.Mode.MULTIPLY);
			ElementoEdit.this.dispatchTakePictureIntent();
		}
	};

	private void setBtnListenerOrDisable(final ImageView btn,
			final ImageView.OnClickListener onClickListener, final String intentName) {
		if (isIntentAvailable(this, intentName)) {
			btn.setOnClickListener(onClickListener);
		} else {
			// btn.setText(this.getText(R.string.cannot).toString() + " " + btn.getText());
			btn.setClickable(false);
		}
	}

	/**
	 * Indicates whether the specified action can be used as an intent. This method queries the
	 * package manager for installed packages that can respond to an intent with the specified
	 * action. If no suitable package is found, this method returns false.
	 * http://android-developers.blogspot.com/2009/01/can-i-use-this-intent.html
	 *
	 * @param context The application's environment.
	 * @param action The Intent action to check for availability.
	 *
	 * @return True if an Intent with the specified action can be sent and responded to, false
	 *         otherwise.
	 */
	public static boolean isIntentAvailable(final Context context, final String action) {
		final PackageManager packageManager = context.getPackageManager();
		final Intent intent = new Intent(action);
		final List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
				PackageManager.MATCH_DEFAULT_ONLY);
		return list.size() > 0;
	}

	private File setUpPhotoFile() throws IOException {

		final File f = this.createImageFile();
		this.mCurrentPhotoPath = f.getAbsolutePath();

		return f;
	}

	private File createImageFile() throws IOException {
		// Create an image file name
		final String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
		final String imageFileName = JPEG_FILE_PREFIX + timeStamp + "_";
		final File storageDir = Environment
				.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);

		final File imageF = File.createTempFile(imageFileName, JPEG_FILE_SUFFIX, storageDir);
		return imageF;
	}

	private void handleBigCameraPhoto() {

		if (this.mCurrentPhotoPath != null) {
			this.setPic();
			this.galleryAddPic();
			// this.mCurrentPhotoPath = null;
		}

	}

	private void setPic() {

		/* There isn't enough memory to open up more than a couple camera photos */
		/* So pre-scale the target bitmap into which the file is decoded */

		/* Get the size of the ImageView */
		int targetW = this.mImageView.getWidth();
		int targetH = this.mImageView.getHeight();

		/* Get the size of the image */
		final BitmapFactory.Options bmOptions = new BitmapFactory.Options();
		bmOptions.inJustDecodeBounds = true;
		BitmapFactory.decodeFile(this.mCurrentPhotoPath, bmOptions);
		final int photoW = bmOptions.outWidth;
		final int photoH = bmOptions.outHeight;

		/* Figure out which way needs to be reduced less */
		int scaleFactor = 1;
		if ((targetW > 0) || (targetH > 0)) {
			targetW = targetW == 0 ? 1 : targetW;
			targetH = targetH == 0 ? 1 : targetH;
			scaleFactor = Math.min(photoW / targetW, photoH / targetH);
		}

		/* Set bitmap options to scale the image decode target */
		bmOptions.inJustDecodeBounds = false;
		bmOptions.inSampleSize = scaleFactor;
		bmOptions.inPurgeable = true;

		/* Decode the JPEG file into a Bitmap */
		final Bitmap bitmap = BitmapFactory.decodeFile(this.mCurrentPhotoPath, bmOptions);

		/* Associate the Bitmap to the ImageView */
		this.mImageView.setImageBitmap(bitmap);
		this.mImageView.setVisibility(View.VISIBLE);
	}

	private void galleryAddPic() {
		final Intent mediaScanIntent = new Intent("android.intent.action.MEDIA_SCANNER_SCAN_FILE");
		final File f = new File(this.mCurrentPhotoPath);
		final Uri contentUri = Uri.fromFile(f);
		mediaScanIntent.setData(contentUri);
		this.sendBroadcast(mediaScanIntent);
	}

	private void eliminarElemento() {

		ElementoEdit.this.mDbHelper.eliminarElemento(ElementoEdit.this.mRowId);

	}

	public void showConfirmDialog() {
		// Create an instance of the dialog fragment and show it
		final DialogFragment dialog = new ConfirmacionEliminarDialogFragment();
		dialog.show(this.getSupportFragmentManager(), "NoticeDialogFragment");
	}

	@Override
	public void onDialogPositiveClick(final DialogFragment dialog) {
		this.eliminarElemento();
		ElementoEdit.this.setResult(RESULT_OK);
		ElementoEdit.this.finish();

	}

	@Override
	public void onDialogNegativeClick(final DialogFragment dialog) {
		dialog.dismiss();

	}

}
